package ltd.hanamaki.study.jdbc.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
import java.util.Stack;

/* 在工具类中 方法尽量使用 静态方法  属性尽量使用 静态*/
public class JDBCUtils {

    /* 连接信息 */
    static String url;
    static String username;
    static String driver;
    static String password;
    static Properties properties;
    static Connection connection;
    /* 加载配置文件中的信息 */
    static {
        try {
//            FileInputStream fileInputStream = new FileInputStream("javaStudy/src/ltd/hanamaki/study/jdbc/util/db.ini");
            InputStream resourceAsStream = JDBCUtils.class.getClassLoader().getResourceAsStream("db.ini");
            properties = new Properties();
            properties.load(resourceAsStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        url = properties.getProperty("url");
        username = properties.getProperty("username");
        password = properties.getProperty("password");
        driver = properties.getProperty("driver");

        /* 加载驱动 */
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 连接数据库的方法
     * @return
     */
    public static Connection getCon() {
        try {
            connection = DriverManager.getConnection(url, username, password);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return connection;
    }

    public static void release(Connection connection, Statement statement, ResultSet resultSet, PreparedStatement preparedStatement) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }


}
